package com.thunder.reader.weibo;

import java.io.File;
import java.util.SortedSet;

import oauth.signpost.OAuth;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.exception.OAuthNotAuthorizedException;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.sina.weibo4j.Status;
import com.sina.weibo4j.Weibo;
import com.sina.weibo4j.WeiboException;
import com.thunder.reader.R;
import com.thunder.reader.provider.Feed;

public class Share2WeiboActivity extends Activity {
    private static final String TAG = "Share2WeiboActivity";
    
    public static final String EXTRA_MESSAGE_TEXT = "message_text";
    public static final String EXTRA_MESSAGE_URL = "message_url";
    public static final String EXTRA_IMAGE_TO_SHARE = "image_to_share";
    
    private static final String CALLBACK_URI = "founderapp://SplashActivity";
    private static final String CONSUMER_KEY = "838435498";
    private static final String CONSUMER_SECRET = "2c418e9f114d93264245a14e9624d869";
    private static final int SHORT_URL_LEN = 20;
    private EditText mMessageEditor;
    private TextView mMessageCounter;
    private Button mActionSend;
    private CommonsHttpOAuthConsumer mOAuthConsumer;
    private OAuthProvider mOAuthProvider;
    private ImageView mImagePreviewer;
    private File mImage2Share;
    private String mAccessToken;
    private String mAccessSecret;
    private String mUserID;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.share2weibo);
        final Intent intent = getIntent();
        final String msg = intent.getStringExtra(EXTRA_MESSAGE_TEXT);
        final String url = intent.getStringExtra(EXTRA_MESSAGE_URL);
        String path = intent.getStringExtra(EXTRA_IMAGE_TO_SHARE);
        mImagePreviewer = (ImageView) findViewById(R.id.share2weibo_image);
        mActionSend = (Button) findViewById(R.id.share2weibo_send);
        mMessageCounter = (TextView) findViewById(R.id.share2weibo_message_counter);
        mMessageEditor = (EditText) findViewById(R.id.share2weibo_message_editor);
        mMessageEditor.addTextChangedListener(new TextWatcher(){
            @Override
            public void afterTextChanged(Editable msg) {
                final int len = msg.length() - url.length() + SHORT_URL_LEN;
                if (len <= 140) {
                    mMessageCounter.setText(getString(R.string.text_count_available, (140-len)));
                    mActionSend.setEnabled(true);
                } else {
                    mMessageCounter.setText(getString(R.string.text_count_overflow, (len-140)));
                    mActionSend.setEnabled(false);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
        });
        mMessageEditor.setText(msg + " " + url);
        if (TextUtils.isEmpty(path)) {
            path = "";
        }
        mImage2Share = new File(path);
        if (!mImage2Share.exists() || mImage2Share.length() < 0) {
            mImagePreviewer.setVisibility(View.GONE);
        }
        final Bitmap bm = BitmapFactory.decodeFile(mImage2Share.getAbsolutePath());
        mImagePreviewer.setImageBitmap(bm);
        mActionSend.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (TextUtils.isEmpty(mAccessToken) || TextUtils.isEmpty(mAccessSecret)) {
                    notifyUser("Please authorize first");
                    authorize();
                    return;
                }
                
                final Weibo weibo = new Weibo();
                weibo.setToken(mAccessToken, mAccessSecret);
                Status status = null;
                try {
                    if (mImage2Share.exists() && mImage2Share.length() > 0) {
                        status = weibo.uploadStatus(mMessageEditor.getText().toString(), mImage2Share);
                    } else {
                        status = weibo.updateStatus(mMessageEditor.getText().toString());
                    }
                } catch (WeiboException e) {
                    e.printStackTrace();
                    Log.e(TAG, "fuck, exception ", e);
                }
                if (status == null || status.getId() == -1) {
                    notifyUser("Failed to share");
                } else {
                    notifyUser("Success on sharing to weibo");
                    finish();
                    setLeaveAnimation();
                }
            }

        });
        
        // query authorize info from database
        final Cursor cursor = getContentResolver().query(Feed.WeiboAccount.CONTENT_URI, 
                Feed.WeiboAccount.PROJECTION, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            mUserID = cursor.getString(Feed.WeiboAccount.USER_ID_INDEX);
            mAccessToken = cursor.getString(Feed.WeiboAccount.ACCESS_TOKEN_INDEX);
            mAccessSecret = cursor.getString(Feed.WeiboAccount.ACCESS_SECRET_INDEX);
        }
        if (cursor != null) {
            cursor.close();
        }
        
        System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
        System.setProperty("weibo4j.oauth.consumerSecret", Weibo.CONSUMER_SECRET);
    }

//    private String getShortUrl(String longUrl) {
//        if (TextUtils.isEmpty(longUrl)) {
//            return "";
//        }
//        String encodedUrl = longUrl;
//        try {
//            encodedUrl = URLEncoder.encode(longUrl, "utf-8");
//        } catch (UnsupportedEncodingException e) {
//        }
////        String requestUrl = "http://api.t.sina.com.cn/short_url/shorten.json";
//        String requestUrl = "https://api.weibo.com/2/short_url/shorten.json";
//        requestUrl += "?source=" + CONSUMER_KEY;
//        requestUrl += "&access_token=" + mAccessToken;
//        requestUrl += "&url=" + encodedUrl;
//        Log.e(TAG, "resq url: " + requestUrl);
//        URL u;
//        try {
//            u = new URL(requestUrl);
//            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
//            conn.setDoInput(false);
//            conn.setDoOutput(true);
//            conn.setConnectTimeout(30*1000);
//            conn.addRequestProperty("url", encodedUrl);
//            conn.addRequestProperty("source", CONSUMER_KEY);
//            conn.addRequestProperty(FeedSettings.PROPERTY_USER_AGENT, FeedSettings.getUserAgent());
//            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
//                Log.e(TAG, "fuck, rc " + conn.getResponseCode() + ", msg " + conn.getResponseMessage());
//                return longUrl;
//            }
//            //            JSONObject obj = new JSONObject(response.getEntity().toString());
//        } catch (MalformedURLException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//        return longUrl;
//    }

    private void notifyUser(final String msg) {
        Toast t = Toast.makeText(Share2WeiboActivity.this, msg, Toast.LENGTH_SHORT);
//        t.setGravity(Gravity.CENTER, 0, 0);
        t.show();
    }
    
    private void authorize() {
        mOAuthConsumer = new CommonsHttpOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        mOAuthProvider = new DefaultOAuthProvider("http://api.t.sina.com.cn/oauth/request_token",
                "http://api.t.sina.com.cn/oauth/access_token",
                "http://api.t.sina.com.cn/oauth/authorize");
        
        // get the request token
        try {
            final String oauthUrl = mOAuthProvider.retrieveRequestToken(mOAuthConsumer, CALLBACK_URI);
            if (TextUtils.isEmpty(oauthUrl)) {
                Log.e(TAG, "fuck, au url is empty");
            }
            Log.e(TAG, "url is: " + oauthUrl);
            final Intent intent = new Intent(getApplication(), LogonWeiboActivity.class);
            intent.putExtra("oauth_url", oauthUrl);
            startActivity(intent);
        } catch (OAuthMessageSignerException e) {
            Log.e(TAG, "exception caught " + e.getMessage());
        } catch (OAuthNotAuthorizedException e) {
            Log.e(TAG, "exception caught " + e.getMessage());
        } catch (OAuthExpectationFailedException e) {
            Log.e(TAG, "exception caught " + e.getMessage());
        } catch (OAuthCommunicationException e) {
            /*
             * Fuck android, you should NEVER forget adding permission "INTERNET", when
             * you are developing networks related App. Otherwise you will get:
             * 'Unable to resolve host "api.t.sina.com.cn": No address associated with hostname'
             */
            Log.e(TAG, "exception caught OAuthCommunicationException " + e.getMessage());
        }
    }
    
    @Override
    public void onNewIntent(Intent intent) {
        Log.e(TAG, "onNewIntent: intent +" + intent);
        final Uri uri = intent.getData();
        if (uri == null) {
            Log.e(TAG, "fuck, uri from authorization intent is null");
            return;
        }
        final String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
        if (TextUtils.isEmpty(verifier)) {
            Log.e(TAG, "WTF, verifier is empty");
            return;
        }
        mOAuthProvider.setOAuth10a(true);
        try {
            mOAuthProvider.retrieveAccessToken(mOAuthConsumer, verifier);
        } catch (OAuthMessageSignerException e) {
            e.printStackTrace();
            Log.e(TAG, "exception caught " + e.getMessage());
            return;
        } catch (OAuthNotAuthorizedException e) {
            e.printStackTrace();
            Log.e(TAG, "exception caught " + e.getMessage());
            return;
        } catch (OAuthExpectationFailedException e) {
            e.printStackTrace();
            Log.e(TAG, "exception caught " + e.getMessage());
            return;
        } catch (OAuthCommunicationException e) {
            e.printStackTrace();
            Log.e(TAG, "exception caught " + e.getMessage());
            return;
        }
        
        // Server response with success, get user id, access token and token secret
        final SortedSet<String> userInfoSet = mOAuthProvider.getResponseParameters().get("user_id");
        if (userInfoSet!= null && !userInfoSet.isEmpty()) {
            mUserID = userInfoSet.first();
        }
        mAccessToken = mOAuthConsumer.getToken();
        mAccessSecret = mOAuthConsumer.getTokenSecret();
        if (TextUtils.isEmpty(mAccessToken) || TextUtils.isEmpty(mAccessSecret)) {
            Log.e(TAG, "shit, access token and access secret are invalid");
            return;
        }
        
        // save authorization data to database for future use not to bother user authorize every time
        getContentResolver().delete(Feed.WeiboAccount.CONTENT_URI, null, null);
        final ContentValues values = new ContentValues(3);
        values.put(Feed.WeiboAccount.USER_ID, mUserID);
        values.put(Feed.WeiboAccount.ACCESS_TOKEN, mAccessToken);
        values.put(Feed.WeiboAccount.ACCESS_SECRET, mAccessSecret);
        getContentResolver().insert(Feed.WeiboAccount.CONTENT_URI, values);
    }

    @Override
    public void onBackPressed() {
	super.onBackPressed();
        setLeaveAnimation();
    }

    private void setLeaveAnimation() {
        overridePendingTransition(R.anim.share2weibo_leave_enter, R.anim.share2weibo_leave_exit);
    }
}